//
//  AppDelegate.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/19.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
       
        setAppearance()
        
        // TODO:测试账号
        let userAccount = QBUserAccountViewModel.sharedInstance.userAccount
        
        print("AppDelegate userAccount:\(userAccount)")
        
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // 创建TabBarVc
        //let tabBarVc = QBMainViewController()
        
        // 设置根控制器
        window?.rootViewController = defaultViewController()
        
        // window?.rootViewController = QBWelcomeViewController()
        
        // window?.rootViewController = QBNewFeatureViewController()
        
        window?.makeKeyAndVisible()
        
        return true
    }
    
    // 设置皮肤
    private func setAppearance() {
        
        // 设置导航栏皮肤
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
    }

    private func defaultViewController() -> UIViewController {
        
        if !QBUserAccountViewModel.sharedInstance.userLogin {
            // 没有登录
            return QBMainViewController()
        }
        
        // 登录过了
        return isNewVersion() ? QBNewFeatureViewController() : QBWelcomeViewController()
    }
    /// 界面切换统一调用这个方法，到时候如果界面切换出问题，直接这个方法里面大断点，方便调试
    /// 外面使用需要拿到对象在调用，比较麻烦
    func switchRootViewController(controller: UIViewController) {
        
        window?.rootViewController = controller
    }
    
    /// 外部调用的切换根控制器方法
    class  func outSwitchRootViewController(controller: UIViewController) {
    
        let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
        
        appDelegate?.switchRootViewController(controller)
    }
    
    /**
     是否是新版本
     
     - returns: 是否是新版本
     */
    private func isNewVersion() -> Bool {
        // 获取当前版本
        let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        print("version:\(version)")
        
        // 获取上一次版本
        let sandboxKey = "sandboxKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().stringForKey(sandboxKey)
        
        print("sandboxVersion:\(sandboxVersion)")
        
        // 对比，不一样就是新版本
        let newVersion = version != sandboxVersion
        
        if newVersion {
            
            NSUserDefaults.standardUserDefaults().setObject(version, forKey: sandboxKey)
            
            NSUserDefaults.standardUserDefaults().synchronize()
        }
        // 返回比较的结果
        return newVersion
    }
}

